﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Serilog;
using Serilog.Extensions.Hosting;

namespace HECore.SerilogWebApi.Filters
{
    public class RequestAuditLogFilter : IResultFilter
    {
        private readonly IDiagnosticContext _diagnosticContext;

        public RequestAuditLogFilter(IDiagnosticContext diagnosticContext) { _diagnosticContext = diagnosticContext; }

        public void OnResultExecuted(ResultExecutedContext context)
        {
            var result = context.Result as ObjectResult;
            var resultJson = JsonConvert.SerializeObject(result?.Value);
            _diagnosticContext.Set("_ResponseBody", resultJson);
        }

        public void OnResultExecuting(ResultExecutingContext context) { }
    }
    public class RequestAuditLogAttribute : TypeFilterAttribute
    {
        public RequestAuditLogAttribute() : base(typeof(RequestAuditLogFilter)) { }
    }
}
